<?php


use Illuminate\Support\Facades\Route;
use App\Models\Site;
use App\Models\Module;

function user($name = null)
{
    if (\Illuminate\Support\Facades\Auth::check()) {
        $user = auth()->user();
        return $name ? $user[$name] : $user;
    }

}

function route_class()
{
    return str_replace('.', '-', Route::currentRouteName());
}

function permission_name($permission, $site, $module)
{

    return 's' . $site['id'] . '-' . $module['name'] . '-' . $permission;
}


function site(Site $site = null)
{
//不传参则取site的值
    if (is_null($site)) {
        $site = session('site');

    }
    //传参则是设置
    if ($site instanceof Site) {
        session(['site' => $site]);
    }

    //如果site不存在，则抛出错误
    if (!($site instanceof Site)) {
        abort(404, '站点不存在');
    }
    return $site;
}

function module(string $name = null)
{
    if (is_null($name)) {
        $module = session('module');

    }
    if (!is_null($name)) {
        $module = app(\App\Services\ModuleService::class)->find($name);
        unset($module['module']);
        session(['module' => $module]);
    }
    if (empty($module)) {
        abort('404', '模块不存在');
    }
    return $module;
}

function access($permission, $force = true, $site = null, $module = null)
{
    $site = $site ?? site();
    $module = $module ?? module();

    if (!\Illuminate\Support\Facades\Auth::check()) return false;

    if (user()->isSuperAdmin || site()['user_id'] == user('id')) {
        return true;
    }


    $permission = permission_name($permission, $site, $module);
    $status = user()->can($permission);
    if ($status == false && $force) {
        abort(403, '没有操作权限');
    }
    return $status;
}

function is_admin()
{
    if (Auth::check()) {

        return user()->isSuperAdmin || site()->user_id == user()->id;
    }

}

function getModelrandNumber($className, string $key = 'id', $num = 1)
{
    $collect = $className::all();
    if ($collect->count() == 0) {
        return null;
    }
    return $collect->random()->$key;
}

//json形式的二维数组，筛选内部的KEY
function filterJsonArrayKey($json, $keys)
{
    if (is_null($json)) {
        return;
    }
    if (is_null($keys)) {
        return $json;
    }
    //数组包裹

    $keys = is_array($keys) ? $keys : [$keys];
    return array_map(function ($v) use ($keys) {

        return array_filter($v, function ($k) use ($keys) {
            return in_array($k, $keys);
        }, ARRAY_FILTER_USE_KEY);

    }, $json);

}
function is_wechat()
{

    return strpos($_SERVER['HTTP_USER_AGENT'], 'micromessenger');
}
